import { login, logout, getInfo, refreshToken } from '@/api/user'
import { userRoute } from '@/api/rbac/menu'
import { menuPermissionsList } from '@/api/rbac/menu-permission'
import { getRefreshToken, getAccessToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter, constantRoutes } from '@/router'
import { treeDataTranslate } from '@/utils'
import Layout from '@/layout'

const getDefaultState = () => {
  return {
    token: getAccessToken(),
    name: '',
    avatar: '',
    shopId: '',
    isAdmin: false,
    roles: [],
    routes: []
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_SHOP_ID: (state, shopId) => {
    state.shopId = shopId
  },
  SET_IS_ADMIN: (state, isAdmin) => {
    state.isAdmin = isAdmin
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_ROUTES: (state, routes) => {
    state.routes = routes
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ principal: username.trim(), credentials: password, sysType: 1 }).then(response => {
        const { data } = response
        commit('SET_TOKEN', data.accessToken)
        setToken(data.accessToken, data.refreshToken)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo().then(response => {
        const { data } = response

        if (!data) {
          return reject('Verification failed, please Login again.')
        }

        const { nickName, avatar, shopId, isAdmin } = data

        commit('SET_NAME', nickName)
        commit('SET_AVATAR', avatar)
        commit('SET_SHOP_ID', shopId)
        commit('SET_IS_ADMIN', isAdmin)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // refresh token
  async refreshToken({ commit }) {
    await refreshToken({ refreshToken: getRefreshToken() }).then(response => {
      const { data } = response
      commit('SET_TOKEN', data.accessToken)
      setToken(data.accessToken, data.refreshToken)
    }).catch(error => {
      removeToken()
    })
  },
  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  },

  listPermissions({ commit, state }) {
    return new Promise((resolve, reject) => {
      if (state.isAdmin) {
        commit('SET_ROLES', [''])
        resolve([''])
        return
      }
      menuPermissionsList().then(res => {
        const permissions = res.data
        console.log(permissions)
        if (!permissions) {
          reject('Verification failed, please Login again.')
        }
        // roles must be a non-empty array
        if (!permissions || permissions.length <= 0) {
          permissions = ['']
        }
        commit('SET_ROLES', permissions)
        resolve(permissions)
      }).catch(error => {
        reject(error)
      })
    })
  },

  generateRoutes({ commit }) {
    return new Promise((resolve, reject) => {
      userRoute().then(response => {
        const menuList = response.data
        for (const menu of menuList) {
          if (menu.component === 'Layout') {
            menu.component = Layout
          } else {
            menu.component = loadView(menu.component)
          }
        }
        const accessedRoutes = treeDataTranslate(menuList)
        const routes = [...constantRoutes, ...accessedRoutes]
        routes.push({ path: '*', redirect: '/404', hidden: true })
        commit('SET_ROUTES', routes)
        resolve(accessedRoutes)
      }).catch(error => {
        reject(error)
      })
    })
  }
}

export const loadView = (view) => { // 路由懒加载
  return () => Promise.resolve(require(`@/views/${view}`).default)
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

